package com.polymer.app.rabbitmq;

import org.apache.log4j.Logger;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.polymer.app.entity.BussinessDO;
import com.polymer.app.service.BussinessService;
import com.polymer.app.utils.LoggerUtil;
import com.rabbitmq.client.Channel;


public class MqReceiver implements ChannelAwareMessageListener{
    private static final Logger logger= Logger.getLogger(MqReceiver.class);
    @Autowired
    private RabbitTemplate template;
    
    @Autowired
    private BussinessService bussinessService;

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        try {
            String msg = new String(message.getBody());
            LoggerUtil.info(logger, "接收消息:{0}", msg);
            BussinessDO bussinessDO = JSON.parseObject(msg, BussinessDO.class);
            int row = bussinessService.saveBus(bussinessDO);
            if(row>0) {
                LoggerUtil.info(logger, "消息处理成功!");
            }else {
                LoggerUtil.info(logger, "消息处理失败!");
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            LoggerUtil.warn(logger, "消息处理异常:{0}",e);
            /*channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);//对于处理不了的异常消息
            BussinessDO bussinessDO = JSON.parseObject(new String(message.getBody()), BussinessDO.class);
            //发送到失败队列
            template.convertAndSend(AmqpConfig.EXCHANGE, AmqpConfig.ROUTINGKEY_FAIL, bussinessDO);*/
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }

}
